import { NextResponse } from 'next/server'
import {generateToken, verifyAuth} from '@/service/auth.mjs'
import { jsonResponse } from '@/utils/index.mjs'
import { httpCode } from '@/utils/httpCode.mjs'
import { headers } from 'next/headers'
const whitelist = ['/login', '/user/refresh-token', '/webhook/build', '/get-verification-code', '/verify-code']
export const config = {
    matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     */
    '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
}
const corsOptions = {
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
export async function middleware(req, res) {
    const routePath = req.nextUrl.pathname
    const origin = req.headers.get('origin') || ''
    // 1.OPTIONS 请求
    // Handle preflighted requests
    const isPreflight = req.method === 'OPTIONS'
    if (isPreflight) {
        const preflightHeaders = {
            ...(true && { 'Access-Control-Allow-Origin': origin }),
            ...corsOptions,
        }
        return NextResponse.json({}, { headers: preflightHeaders })
    }

    // 2.验证token
    if (!whitelist.includes(routePath)) {
        const headersList = headers()
        const token = headersList.get('authorization')
        try {
            await verifyAuth(req)
        } catch (err) {
            if (!token) {
                return jsonResponse(httpCode.NEED_LOGIN, {})
            }
            if (err.code === 'ERR_JWT_EXPIRED') {
                // 如果过期时间在2小时内，则刷新token，否者重新登录
                if ((new Date().getTime() - new Date(err.payload.exp * 1000).getTime()) > 2 * 60 * 60 * 1000) {
                    return jsonResponse(httpCode.NEED_LOGIN, {})
                }
                return jsonResponse(httpCode.OK, { token: await generateToken({ user_id: err.payload.user_id})})
            }

        }
    }
    const response = NextResponse.next()
    return response
}
